package org.ljy.lotterysystem.common.utils;

//用来序列化和反序列的工具类


import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {

    //序列化 -- 把对象转成json
    //反序列化 -- 把json转成对象



    //1.构造单例
    private static final ObjectMapper OBJECT_MAPPER;

    private JacksonUtil() {}

    static {
        OBJECT_MAPPER = new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }
    //2.统一封装，用来统一处理异常 (这两个方法用来定义objectMapper对象)

    private static  <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);//JsonProcessingException
    }

    private static  <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();//用来创建objectMapper对象
        } catch (Exception var4) {//下面作统一异常处理
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }

            throw new IllegalStateException(var4);
        }
    }


    //3.对外开发工具类

    /**
     *  序列化方法
     *
     * @param value 待序列化对象
     * @return 字符串
     */
    public static String writeValueAsString(Object value) {
        return JacksonUtil.tryParse(()-> {
            return JacksonUtil.getObjectMapper().writeValueAsString(value);
        });
    }


    /**
     * 反序列化方法
     *
     * @param content 源
     * @param type 需要反序列成的对象
     * @return
     * @param <T>
     */
    public static <T> T readValue(String content, Class<T> type) {
        return JacksonUtil.tryParse(() -> {
            return JacksonUtil.getObjectMapper().readValue(content, type);
        });

    }

    /**
     * 反序列化List方法
     * @param content
     * @param paramClasses
     * @return
     * @param <T>
     */
    public static <T> T readListValue(String content, Class<?> paramClasses) {
        //1.
        JavaType type = JacksonUtil.getObjectMapper().getTypeFactory()
                                    .constructParametricType(List.class, paramClasses);
        //2.
        return JacksonUtil.tryParse(() -> {
            return JacksonUtil.getObjectMapper().readValue(content, type);
        });
    }



}
